'use client';

import { useState, useRef } from 'react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Play,
  RotateCcw,
  Save,
  Share,
  Settings,
  Maximize2,
  Minimize2,
  Terminal,
  FileText,
  Loader2,
} from 'lucide-react';

interface CodeEditorProps {
  initialCode?: string;
  language?: string;
  theme?: 'light' | 'dark';
  readOnly?: boolean;
  showOutput?: boolean;
  showConsole?: boolean;
  height?: string;
  className?: string;
  onCodeChange?: (code: string) => void;
  onRun?: (code: string) => Promise<{ output: string; error?: string }>;
}

/**
 * 在线代码编辑器组件
 * 支持代码编辑、运行和结果展示
 */
export function CodeEditor({
  initialCode = '',
  language = 'cangjie',
  readOnly = false,
  showOutput = true,
  showConsole = true,
  height = '400px',
  className,
  onCodeChange,
  onRun,
}: CodeEditorProps) {
  const [code, setCode] = useState(initialCode);
  const [output, setOutput] = useState('');
  const [error, setError] = useState('');
  const [isRunning, setIsRunning] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [activeTab, setActiveTab] = useState('editor');
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  /**
   * 处理代码变化
   */
  const handleCodeChange = (newCode: string) => {
    setCode(newCode);
    onCodeChange?.(newCode);
  };

  /**
   * 运行代码
   */
  const runCode = async () => {
    if (!onRun) {
      // 模拟代码执行
      setIsRunning(true);
      setError('');

      setTimeout(() => {
        if (language === 'cangjie' || language === 'cj') {
          setOutput(simulateCangjieExecution(code));
        } else {
          setOutput('代码执行结果将在这里显示...');
        }
        setIsRunning(false);
        setActiveTab('output');
      }, 1000);
      return;
    }

    try {
      setIsRunning(true);
      setError('');
      const result = await onRun(code);
      setOutput(result.output);
      if (result.error) {
        setError(result.error);
      }
      setActiveTab('output');
    } catch (err) {
      setError(err instanceof Error ? err.message : '执行出错');
    } finally {
      setIsRunning(false);
    }
  };

  /**
   * 模拟仓颉代码执行
   */
  const simulateCangjieExecution = (code: string): string => {
    const lines = code.split('\n');
    const output: string[] = [];

    // 简单的模拟执行逻辑
    for (const line of lines) {
      const trimmed = line.trim();

      // 模拟 println 输出
      const printMatch = trimmed.match(/println\("([^"]+)"\)/);
      if (printMatch) {
        output.push(printMatch[1]);
        continue;
      }

      // 模拟变量声明
      const varMatch = trimmed.match(/let\s+(\w+)\s*=\s*(.+)/);
      if (varMatch) {
        output.push(`变量 ${varMatch[1]} 已定义`);
        continue;
      }

      // 模拟函数定义
      const funcMatch = trimmed.match(/func\s+(\w+)\s*\(/);
      if (funcMatch) {
        output.push(`函数 ${funcMatch[1]} 已定义`);
        continue;
      }

      // 模拟类定义
      const classMatch = trimmed.match(/class\s+(\w+)/);
      if (classMatch) {
        output.push(`类 ${classMatch[1]} 已定义`);
        continue;
      }
    }

    if (output.length === 0) {
      return '程序执行完成，无输出。';
    }

    return output.join('\n');
  };

  /**
   * 重置代码
   */
  const resetCode = () => {
    setCode(initialCode);
    setOutput('');
    setError('');
    onCodeChange?.(initialCode);
  };

  /**
   * 保存代码
   */
  const saveCode = () => {
    const blob = new Blob([code], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `code.${language === 'cangjie' || language === 'cj' ? 'cj' : 'txt'}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  /**
   * 分享代码
   */
  const shareCode = async () => {
    try {
      await navigator.clipboard.writeText(code);
      alert('代码已复制到剪贴板！');
    } catch (err) {
      console.error('Failed to copy code:', err);
    }
  };

  /**
   * 处理键盘快捷键
   */
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.ctrlKey || e.metaKey) {
      switch (e.key) {
        case 'Enter':
          e.preventDefault();
          runCode();
          break;
        case 's':
          e.preventDefault();
          saveCode();
          break;
        case 'r':
          e.preventDefault();
          resetCode();
          break;
      }
    }

    // Tab 键处理
    if (e.key === 'Tab') {
      e.preventDefault();
      const textarea = e.target as HTMLTextAreaElement;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const newCode = code.substring(0, start) + '  ' + code.substring(end);
      setCode(newCode);

      // 设置光标位置
      setTimeout(() => {
        textarea.selectionStart = textarea.selectionEnd = start + 2;
      }, 0);
    }
  };

  return (
    <div
      className={cn(
        'border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-white dark:bg-gray-900',
        isFullscreen && 'fixed inset-0 z-50 rounded-none',
        className
      )}
    >
      {/* 工具栏 */}
      <div className="flex items-center justify-between px-4 py-2 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center space-x-2">
          <Badge className="bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300">
            {language.toUpperCase()}
          </Badge>
          {readOnly && (
            <Badge variant="outline" className="text-xs">
              只读
            </Badge>
          )}
        </div>

        <div className="flex items-center space-x-1">
          <Button
            size="sm"
            variant="ghost"
            onClick={runCode}
            disabled={isRunning || readOnly}
            className="h-7 px-2 text-xs"
          >
            {isRunning ? (
              <Loader2 className="h-3 w-3 mr-1 animate-spin" />
            ) : (
              <Play className="h-3 w-3 mr-1" />
            )}
            运行
          </Button>

          <Button
            size="sm"
            variant="ghost"
            onClick={resetCode}
            disabled={readOnly}
            className="h-7 px-2 text-xs"
          >
            <RotateCcw className="h-3 w-3" />
          </Button>

          <Button
            size="sm"
            variant="ghost"
            onClick={saveCode}
            className="h-7 px-2 text-xs"
          >
            <Save className="h-3 w-3" />
          </Button>

          <Button
            size="sm"
            variant="ghost"
            onClick={shareCode}
            className="h-7 px-2 text-xs"
          >
            <Share className="h-3 w-3" />
          </Button>

          <Button
            size="sm"
            variant="ghost"
            onClick={() => setIsFullscreen(!isFullscreen)}
            className="h-7 px-2 text-xs"
          >
            {isFullscreen ? (
              <Minimize2 className="h-3 w-3" />
            ) : (
              <Maximize2 className="h-3 w-3" />
            )}
          </Button>
        </div>
      </div>

      {/* 主内容区域 */}
      <div
        className="flex flex-col lg:flex-row"
        style={{ height: isFullscreen ? 'calc(100vh - 60px)' : height }}
      >
        {/* 编辑器区域 */}
        <div className="flex-1 flex flex-col">
          <Tabs
            value={activeTab}
            onValueChange={setActiveTab}
            className="flex-1 flex flex-col"
          >
            <TabsList className="grid w-full grid-cols-2 lg:grid-cols-3 rounded-none border-b">
              <TabsTrigger
                value="editor"
                className="flex items-center space-x-1"
              >
                <FileText className="h-4 w-4" />
                <span>编辑器</span>
              </TabsTrigger>
              {showOutput && (
                <TabsTrigger
                  value="output"
                  className="flex items-center space-x-1"
                >
                  <Terminal className="h-4 w-4" />
                  <span>输出</span>
                  {error && <div className="w-2 h-2 bg-red-500 rounded-full" />}
                </TabsTrigger>
              )}
              {showConsole && (
                <TabsTrigger
                  value="console"
                  className="flex items-center space-x-1 hidden lg:flex"
                >
                  <Settings className="h-4 w-4" />
                  <span>控制台</span>
                </TabsTrigger>
              )}
            </TabsList>

            <TabsContent value="editor" className="flex-1 m-0">
              <div className="relative h-full">
                <textarea
                  ref={textareaRef}
                  value={code}
                  onChange={e => handleCodeChange(e.target.value)}
                  onKeyDown={handleKeyDown}
                  readOnly={readOnly}
                  className="w-full h-full p-4 font-mono text-sm bg-white dark:bg-gray-950 text-gray-800 dark:text-gray-200 border-0 outline-none resize-none"
                  placeholder={`在这里输入${language === 'cangjie' || language === 'cj' ? '仓颉' : language}代码...`}
                  spellCheck={false}
                />

                {/* 行号 */}
                <div className="absolute left-0 top-0 p-4 text-gray-400 dark:text-gray-600 text-sm font-mono pointer-events-none select-none">
                  {code.split('\n').map((_, index) => (
                    <div key={index} className="leading-5">
                      {index + 1}
                    </div>
                  ))}
                </div>
              </div>
            </TabsContent>

            {showOutput && (
              <TabsContent value="output" className="flex-1 m-0">
                <div className="h-full p-4 bg-gray-50 dark:bg-gray-900 overflow-auto">
                  {error ? (
                    <div className="text-red-600 dark:text-red-400 font-mono text-sm whitespace-pre-wrap">
                      <div className="font-semibold mb-2">执行错误:</div>
                      {error}
                    </div>
                  ) : output ? (
                    <div className="text-gray-800 dark:text-gray-200 font-mono text-sm whitespace-pre-wrap">
                      {output}
                    </div>
                  ) : (
                    <div className="text-gray-500 dark:text-gray-400 text-sm italic">
                      点击运行按钮执行代码...
                    </div>
                  )}
                </div>
              </TabsContent>
            )}

            {showConsole && (
              <TabsContent
                value="console"
                className="flex-1 m-0 hidden lg:block"
              >
                <div className="h-full p-4 bg-black text-green-400 font-mono text-sm overflow-auto">
                  <div className="mb-2">CActor 代码编辑器控制台</div>
                  <div className="text-gray-500">快捷键:</div>
                  <div className="text-gray-500">Ctrl+Enter: 运行代码</div>
                  <div className="text-gray-500">Ctrl+S: 保存代码</div>
                  <div className="text-gray-500">Ctrl+R: 重置代码</div>
                  <div className="text-gray-500">Tab: 缩进</div>
                </div>
              </TabsContent>
            )}
          </Tabs>
        </div>
      </div>

      {/* 状态栏 */}
      <div className="px-4 py-1 bg-gray-100 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 text-xs text-gray-500 dark:text-gray-400 flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <span>行: {code.split('\n').length}</span>
          <span>字符: {code.length}</span>
          <span>语言: {language}</span>
        </div>

        <div className="flex items-center space-x-2">
          {isRunning && (
            <div className="flex items-center space-x-1">
              <Loader2 className="h-3 w-3 animate-spin" />
              <span>运行中...</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/**
 * 代码示例展示组件
 */
interface CodeExampleProps {
  title: string;
  description?: string;
  code: string;
  language?: string;
  editable?: boolean;
  runnable?: boolean;
  className?: string;
}

export function CodeExample({
  title,
  description,
  code,
  language = 'cangjie',
  editable = true,
  runnable = true,
  className,
}: CodeExampleProps) {
  return (
    <div className={cn('space-y-4', className)}>
      <div>
        <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
          {title}
        </h3>
        {description && (
          <p className="text-gray-600 dark:text-gray-400 text-sm">
            {description}
          </p>
        )}
      </div>

      <CodeEditor
        initialCode={code}
        language={language}
        readOnly={!editable}
        showOutput={runnable}
        height="300px"
      />
    </div>
  );
}
